<template>
  <div class="export-manager">
    <div class="manager-header">
      <h3 class="manager-title">
        <el-icon><Download /></el-icon>
        导出管理
      </h3>
      <div class="manager-actions">
        <el-button 
          type="primary" 
          :icon="Download"
          @click="showExportDialog"
          :disabled="!canvasElement"
        >
          导出图片
        </el-button>
        <el-button 
          :icon="DocumentCopy"
          @click="copyContent"
          :disabled="!hasContent"
        >
          复制内容
        </el-button>
      </div>
    </div>
    
    <!-- 快速导出选项 -->
    <div class="quick-export">
      <div class="quick-export-title">快速导出</div>
      <div class="quick-export-buttons">
        <el-button 
          size="small"
          @click="quickExport('png', 'original')"
          :loading="exporting && currentExport === 'png-original'"
        >
          PNG 原尺寸
        </el-button>
        <el-button 
          size="small"
          @click="quickExport('jpg', 'original')"
          :loading="exporting && currentExport === 'jpg-original'"
        >
          JPG 原尺寸
        </el-button>
        <el-button 
          size="small"
          @click="quickExport('png', 'social')"
          :loading="exporting && currentExport === 'png-social'"
        >
          PNG 社交尺寸
        </el-button>
      </div>
    </div>
    
    <!-- 导出历史 -->
    <div class="export-history" v-if="exportHistory.length > 0">
      <div class="history-header">
        <div class="history-title">导出历史</div>
        <el-button 
          text 
          size="small"
          @click="clearHistory"
        >
          清空历史
        </el-button>
      </div>
      
      <div class="history-list">
        <div
          v-for="(item, index) in exportHistory"
          :key="index"
          class="history-item"
        >
          <div class="history-preview">
            <img :src="item.thumbnail" :alt="item.name" />
          </div>
          
          <div class="history-info">
            <div class="history-name">{{ item.name }}</div>
            <div class="history-meta">
              <span>{{ item.format.toUpperCase() }}</span>
              <span>{{ item.width }}×{{ item.height }}</span>
              <span>{{ formatFileSize(item.size) }}</span>
              <span>{{ formatTime(item.createdAt) }}</span>
            </div>
          </div>
          
          <div class="history-actions">
            <el-button 
              type="primary" 
              :icon="Download"
              size="small"
              @click="downloadHistoryItem(item)"
            >
              下载
            </el-button>
            <el-button 
              type="info" 
              :icon="Share"
              size="small"
              @click="shareHistoryItem(item)"
            >
              分享
            </el-button>
            <el-button 
              type="danger" 
              :icon="Delete"
              size="small"
              @click="deleteHistoryItem(index)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 导出设置对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="导出设置"
      width="600px"
      :before-close="handleCloseExportDialog"
    >
      <div class="export-dialog-content">
        <!-- 预览区域 -->
        <div class="export-preview">
          <div class="preview-header">
            <h4>预览</h4>
            <div class="preview-info">
              {{ exportConfig.width }}×{{ exportConfig.height }}px
              {{ exportConfig.format.toUpperCase() }}
            </div>
          </div>
          <div class="preview-container">
            <div 
              class="preview-canvas"
              :style="previewStyle"
            >
              <div class="preview-placeholder">
                <el-icon size="32"><Picture /></el-icon>
                <span>导出预览</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 导出配置 -->
        <div class="export-config">
          <el-form :model="exportConfig" label-width="100px">
            <el-form-item label="导出格式">
              <el-radio-group v-model="exportConfig.format" @change="handleFormatChange">
                <el-radio-button label="png">PNG</el-radio-button>
                <el-radio-button label="jpg">JPG</el-radio-button>
                <el-radio-button label="webp">WebP</el-radio-button>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="图片质量" v-if="exportConfig.format !== 'png'">
              <el-slider
                v-model="exportConfig.quality"
                :min="0.1"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatQualityTooltip"
              />
            </el-form-item>
            
            <el-form-item label="导出尺寸">
              <el-radio-group v-model="exportConfig.sizeType" @change="handleSizeTypeChange">
                <el-radio label="original">原始尺寸</el-radio>
                <el-radio label="preset">预设尺寸</el-radio>
                <el-radio label="custom">自定义</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="预设尺寸" v-if="exportConfig.sizeType === 'preset'">
              <el-select v-model="exportConfig.presetSize" @change="handlePresetSizeChange">
                <el-option label="Instagram 方图 (1080×1080)" value="instagram-square" />
                <el-option label="Instagram 故事 (1080×1920)" value="instagram-story" />
                <el-option label="Facebook 封面 (1200×630)" value="facebook-cover" />
                <el-option label="Twitter 头图 (1500×500)" value="twitter-header" />
                <el-option label="微信公众号封面 (900×500)" value="wechat-cover" />
                <el-option label="小红书 (1242×1660)" value="xiaohongshu" />
                <el-option label="抖音封面 (1080×1920)" value="douyin-cover" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="自定义尺寸" v-if="exportConfig.sizeType === 'custom'">
              <div class="size-inputs">
                <el-input-number
                  v-model="exportConfig.width"
                  :min="100"
                  :max="4000"
                  placeholder="宽度"
                  @change="handleSizeChange"
                />
                <span>×</span>
                <el-input-number
                  v-model="exportConfig.height"
                  :min="100"
                  :max="4000"
                  placeholder="高度"
                  @change="handleSizeChange"
                />
                <el-button 
                  text 
                  size="small"
                  @click="maintainAspectRatio"
                >
                  保持比例
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="背景透明" v-if="exportConfig.format === 'png'">
              <el-switch 
                v-model="exportConfig.transparent"
                active-text="透明"
                inactive-text="不透明"
              />
            </el-form-item>
            
            <el-form-item label="导出DPI">
              <el-radio-group v-model="exportConfig.dpi">
                <el-radio-button :label="72">72 DPI (屏幕)</el-radio-button>
                <el-radio-button :label="150">150 DPI (高清)</el-radio-button>
                <el-radio-button :label="300">300 DPI (印刷)</el-radio-button>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="文件名">
              <el-input
                v-model="exportConfig.filename"
                placeholder="输入文件名"
              >
                <template #append>
                  .{{ exportConfig.format }}
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <div class="export-dialog-footer">
          <div class="export-info">
            <span>预计文件大小: {{ estimatedFileSize }}</span>
          </div>
          <div class="export-actions">
            <el-button @click="exportDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="confirmExport"
              :loading="exporting"
            >
              {{ exporting ? '导出中...' : '开始导出' }}
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    
    <!-- 导出进度对话框 -->
    <el-dialog
      v-model="progressVisible"
      title="导出进度"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="export-progress">
        <div class="progress-info">
          <div class="progress-text">{{ progressText }}</div>
          <div class="progress-detail">{{ progressDetail }}</div>
        </div>
        
        <el-progress 
          :percentage="progressPercentage" 
          :status="progressStatus"
          :stroke-width="8"
        />
        
        <div class="progress-actions" v-if="progressStatus !== 'active'">
          <el-button 
            v-if="progressStatus === 'success'"
            type="primary" 
            @click="downloadResult"
          >
            下载文件
          </el-button>
          <el-button 
            v-if="progressStatus === 'success'"
            type="success" 
            @click="shareResult"
          >
            分享结果
          </el-button>
          <el-button 
            @click="closeProgress"
          >
            {{ progressStatus === 'success' ? '完成' : '关闭' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Download, DocumentCopy, Picture, Share, Delete 
} from '@element-plus/icons-vue'
import html2canvas from 'html2canvas'
import { formatFileSize, formatTime, copyToClipboard } from '@/utils'

interface ExportHistoryItem {
  name: string
  format: string
  width: number
  height: number
  size: number
  createdAt: string
  dataUrl: string
  thumbnail: string
}

interface Props {
  canvasElement?: HTMLElement
  originalWidth?: number
  originalHeight?: number
}

interface Emits {
  (e: 'export-start'): void
  (e: 'export-complete', result: any): void
  (e: 'export-error', error: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const exportDialogVisible = ref(false)
const progressVisible = ref(false)
const exporting = ref(false)
const currentExport = ref('')
const exportHistory = ref<ExportHistoryItem[]>([])

const exportConfig = reactive({
  format: 'png',
  quality: 0.9,
  sizeType: 'original',
  presetSize: 'instagram-square',
  width: 800,
  height: 600,
  transparent: false,
  dpi: 72,
  filename: `图文作品_${Date.now()}`
})

const progressText = ref('准备导出...')
const progressDetail = ref('')
const progressPercentage = ref(0)
const progressStatus = ref<'active' | 'success' | 'exception'>('active')
const exportResult = ref<any>(null)

// 计算属性
const hasContent = computed(() => !!props.canvasElement)

const previewStyle = computed(() => ({
  width: '200px',
  height: `${(exportConfig.height / exportConfig.width) * 200}px`,
  maxHeight: '150px',
  background: '#f5f5f5',
  border: '1px solid #ddd',
  borderRadius: '4px',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center'
}))

const estimatedFileSize = computed(() => {
  const pixels = exportConfig.width * exportConfig.height
  let bytesPerPixel = 4 // RGBA
  
  switch (exportConfig.format) {
    case 'jpg':
      bytesPerPixel = 3 * exportConfig.quality
      break
    case 'webp':
      bytesPerPixel = 2 * exportConfig.quality
      break
    case 'png':
      bytesPerPixel = exportConfig.transparent ? 4 : 3
      break
  }
  
  const estimatedBytes = pixels * bytesPerPixel
  return formatFileSize(estimatedBytes)
})

// 监听原始尺寸变化
watch(() => [props.originalWidth, props.originalHeight], ([width, height]) => {
  if (width && height) {
    exportConfig.width = width
    exportConfig.height = height
  }
}, { immediate: true })

// 方法
const showExportDialog = () => {
  exportDialogVisible.value = true
}

const quickExport = async (format: string, sizeType: string) => {
  currentExport.value = `${format}-${sizeType}`
  
  const config = {
    format,
    quality: format === 'jpg' ? 0.9 : 1,
    sizeType,
    width: sizeType === 'social' ? 1080 : (props.originalWidth || 800),
    height: sizeType === 'social' ? 1080 : (props.originalHeight || 600),
    filename: `快速导出_${Date.now()}`
  }
  
  await performExport(config)
  currentExport.value = ''
}

const copyContent = async () => {
  if (!props.canvasElement) {
    ElMessage.warning('没有可复制的内容')
    return
  }
  
  try {
    const canvas = await html2canvas(props.canvasElement)
    
    // 将canvas转换为blob
    canvas.toBlob(async (blob) => {
      if (blob) {
        try {
          await navigator.clipboard.write([
            new ClipboardItem({ 'image/png': blob })
          ])
          ElMessage.success('内容已复制到剪贴板')
        } catch (error) {
          // 降级方案：复制dataURL
          const dataUrl = canvas.toDataURL()
          await copyToClipboard(dataUrl)
          ElMessage.success('图片链接已复制到剪贴板')
        }
      }
    })
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

const handleFormatChange = () => {
  // 格式变化处理
}

const handleSizeTypeChange = () => {
  if (exportConfig.sizeType === 'original') {
    exportConfig.width = props.originalWidth || 800
    exportConfig.height = props.originalHeight || 600
  } else if (exportConfig.sizeType === 'preset') {
    handlePresetSizeChange()
  }
}

const handlePresetSizeChange = () => {
  const presets: Record<string, [number, number]> = {
    'instagram-square': [1080, 1080],
    'instagram-story': [1080, 1920],
    'facebook-cover': [1200, 630],
    'twitter-header': [1500, 500],
    'wechat-cover': [900, 500],
    'xiaohongshu': [1242, 1660],
    'douyin-cover': [1080, 1920]
  }
  
  const [width, height] = presets[exportConfig.presetSize] || [800, 600]
  exportConfig.width = width
  exportConfig.height = height
}

const handleSizeChange = () => {
  // 尺寸变化处理
}

const maintainAspectRatio = () => {
  if (props.originalWidth && props.originalHeight) {
    const aspectRatio = props.originalWidth / props.originalHeight
    exportConfig.height = Math.round(exportConfig.width / aspectRatio)
  }
}

const formatQualityTooltip = (value: number) => {
  return `${Math.round(value * 100)}%`
}

const confirmExport = async () => {
  exportDialogVisible.value = false
  await performExport(exportConfig)
}

const performExport = async (config: any) => {
  if (!props.canvasElement) {
    ElMessage.error('没有可导出的内容')
    return
  }
  
  exporting.value = true
  progressVisible.value = true
  progressPercentage.value = 0
  progressStatus.value = 'active'
  progressText.value = '准备导出...'
  progressDetail.value = '正在初始化导出设置'
  
  emit('export-start')
  
  try {
    // 模拟进度更新
    const updateProgress = (percentage: number, text: string, detail: string) => {
      progressPercentage.value = percentage
      progressText.value = text
      progressDetail.value = detail
    }
    
    updateProgress(20, '正在渲染画布...', '生成高质量图像')
    
    // 计算缩放比例
    const scale = Math.max(
      config.width / (props.originalWidth || 800),
      config.height / (props.originalHeight || 600)
    ) * (config.dpi / 72)
    
    updateProgress(40, '正在处理图像...', '应用导出设置')
    
    const canvas = await html2canvas(props.canvasElement, {
      backgroundColor: config.transparent ? null : '#ffffff',
      scale: scale,
      width: config.width,
      height: config.height,
      useCORS: true,
      allowTaint: true
    })
    
    updateProgress(70, '正在生成文件...', '压缩和优化图像')
    
    // 转换为指定格式
    const dataUrl = canvas.toDataURL(`image/${config.format}`, config.quality)
    
    updateProgress(90, '正在保存文件...', '准备下载')
    
    // 创建下载链接
    const link = document.createElement('a')
    link.download = `${config.filename}.${config.format}`
    link.href = dataUrl
    link.click()
    
    // 添加到历史记录
    const historyItem: ExportHistoryItem = {
      name: `${config.filename}.${config.format}`,
      format: config.format,
      width: config.width,
      height: config.height,
      size: Math.round(dataUrl.length * 0.75), // 估算文件大小
      createdAt: new Date().toISOString(),
      dataUrl: dataUrl,
      thumbnail: dataUrl
    }
    
    exportHistory.value.unshift(historyItem)
    
    // 限制历史记录数量
    if (exportHistory.value.length > 10) {
      exportHistory.value = exportHistory.value.slice(0, 10)
    }
    
    updateProgress(100, '导出完成', '文件已保存到下载文件夹')
    progressStatus.value = 'success'
    exportResult.value = historyItem
    
    emit('export-complete', historyItem)
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    progressStatus.value = 'exception'
    progressText.value = '导出失败'
    progressDetail.value = '请检查内容并重试'
    emit('export-error', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

const downloadHistoryItem = (item: ExportHistoryItem) => {
  const link = document.createElement('a')
  link.download = item.name
  link.href = item.dataUrl
  link.click()
  ElMessage.success('开始下载')
}

const shareHistoryItem = async (item: ExportHistoryItem) => {
  try {
    const shareText = `我用AI图文管理系统创作了一张图片：${item.name}`
    await copyToClipboard(shareText)
    ElMessage.success('分享内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('分享失败')
  }
}

const deleteHistoryItem = (index: number) => {
  exportHistory.value.splice(index, 1)
  ElMessage.success('已删除')
}

const clearHistory = () => {
  exportHistory.value = []
  ElMessage.success('历史记录已清空')
}

const handleCloseExportDialog = () => {
  exportDialogVisible.value = false
}

const downloadResult = () => {
  if (exportResult.value) {
    downloadHistoryItem(exportResult.value)
  }
}

const shareResult = () => {
  if (exportResult.value) {
    shareHistoryItem(exportResult.value)
  }
}

const closeProgress = () => {
  progressVisible.value = false
  exportResult.value = null
}
</script>

<style scoped>
.export-manager {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.manager-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.manager-actions {
  display: flex;
  gap: 10px;
}

/* 快速导出样式 */
.quick-export {
  margin-bottom: 25px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 15px;
}

.quick-export-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
  color: rgba(255, 255, 255, 0.8);
}

.quick-export-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

/* 导出历史样式 */
.export-history {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 15px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 10px;
}

.history-preview {
  width: 50px;
  height: 50px;
  flex-shrink: 0;
}

.history-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 5px;
}

.history-info {
  flex: 1;
  min-width: 0;
}

.history-name {
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-meta {
  display: flex;
  gap: 10px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
}

.history-actions {
  display: flex;
  gap: 5px;
}

/* 导出对话框样式 */
.export-dialog-content {
  display: grid;
  grid-template-columns: 200px 1fr;
  gap: 20px;
}

.export-preview {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.preview-info {
  font-size: 12px;
  color: #666;
}

.preview-container {
  display: flex;
  justify-content: center;
}

.preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  color: #999;
  font-size: 12px;
}

.export-config {
  min-width: 0;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.size-inputs span {
  color: #666;
  font-weight: bold;
}

.export-dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.export-info {
  font-size: 12px;
  color: #666;
}

.export-actions {
  display: flex;
  gap: 10px;
}

/* 进度对话框样式 */
.export-progress {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-info {
  text-align: center;
}

.progress-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.progress-detail {
  font-size: 12px;
  color: #666;
}

.progress-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .export-manager {
    padding: 15px;
  }
  
  .manager-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .manager-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .quick-export-buttons {
    justify-content: space-between;
  }
  
  .history-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .history-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .export-dialog-content {
    grid-template-columns: 1fr;
  }
  
  .export-dialog-footer {
    flex-direction: column;
    gap: 15px;
  }
}
</style>